using UnityEngine;

public class SkyColliderUpdater : MonoBehaviour
{
    public MeshRenderer m_meshRender;
    public string m_keyAmount = "_Amount";
    public string m_keyAngle = "_Angle";
    public bool isLeftSky;

    public GameObject[] m_faceColliders;
    private bool m_destroyed;
    private int m_timerId;
    private MaterialPropertyBlock m_propBlock;
    private void OnEnable()
    {
        m_destroyed = false;
        m_timerId = TimerAgent.Instance.RegistLoop(UpdateColliderShow, 0.5f);
    }

    private void Start()
    {
        m_propBlock = new MaterialPropertyBlock();
        m_propBlock.SetFloat(m_keyAmount, 0.55f);
        m_propBlock.SetFloat(m_keyAngle, 0);
        m_meshRender.SetPropertyBlock(m_propBlock);
    }

    private void OnDisable()
    {
        m_destroyed = true;
        TimerAgent.Instance.StopTimer(m_timerId);
    }

    private bool UpdateColliderShow()
    {
        if (!Camera.main)
            return false;

        var camraPos = Camera.main.transform.position;
        var horizontal = false;
        for (int i = 0; i < m_faceColliders.Length; i++)
        {
            var target = m_faceColliders[i];
            var forward = target.transform.forward;
            if (Vector3.Angle(forward, target.transform.position - camraPos) < 90)
            {
                target.gameObject.SetActive(isLeftSky);
            }
            else
            {
                target.gameObject.SetActive(!isLeftSky);
            }

            if (!horizontal && Vector3.Angle(forward, Vector3.right) < 1f)
            {
                horizontal = true;
            }
        }
        if (horizontal)
        {
            m_propBlock.SetFloat(m_keyAmount, 0.499f);
            var eulerAngle = transform.eulerAngles.y;
            if (!isLeftSky)
            {
                eulerAngle = 180 - eulerAngle;
            }
            var angle = (eulerAngle + 360) % 360;
            angle = angle > 315 ? angle - 360 : angle;
            m_propBlock.SetFloat(m_keyAngle, angle);
            m_meshRender.SetPropertyBlock(m_propBlock);
        }
        else
        {
            m_propBlock.SetFloat(m_keyAmount, 0.55f);
            m_propBlock.SetFloat(m_keyAngle, 0);
            m_meshRender.SetPropertyBlock(m_propBlock);
        }
        return m_destroyed;
    }
}
